package com.ray.base.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ray.base.builder.*;
import com.ray.base.check.MaterialModelCheck;
import com.ray.base.enums.TemplateTypeEnum;
import com.ray.base.service.*;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.dto.MaterialTemplateQueryDTO;
import com.ray.base.table.dto.TemplateQueryDTO;
import com.ray.base.table.entity.*;
import com.ray.base.table.params.technology.TechnologyCreateParams;
import com.ray.base.table.vo.material.PropVO;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.base.table.vo.technology.TechnologyGoodsVO;
import com.ray.base.table.vo.technology.TechnologyVO;
import com.ray.common.Perifx;
import com.ray.common.check.AbstractCheck;
import com.ray.util.CodeCreateUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 工艺
 * @Class: TechnologyApi
 * @Package com.ray.base.api
 * @date 2020/6/27 12:56
 * @company <p></p>
 *@updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class TechnologyApi {

    @Autowired
    private BaseMaterialModelService baseMaterialModelService;
    @Autowired
    private BaseTechnologyService baseTechnologyService;
    @Autowired
    private BaseTechnologyRecordService baseTechnologyRecordService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private BaseTemplateService baseTemplateService;
    @Autowired
    private BaseTemplateExtendService baseTemplateExtendService;

    /**
     * 编辑产品规格
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> saveTechnology(TechnologyCreateParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询规格是否存在
        BaseMaterialModel materialModel = baseMaterialModelService.queryMaterialModelByMaterialModelCode(editParams.getModelCode(),loginUser);
        new MaterialModelCheck(materialModel).checkNull("规格不存在");
        //删除技术工艺
        baseTechnologyService.deleteByCode(editParams.getTechnologyCode(),loginUser);
        TechnologyBuilder technologyBuilder = new TechnologyBuilder();
        technologyBuilder.append(editParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //编辑产品规格信息
        if (!baseTechnologyService.save(technologyBuilder.bulid())) {
            log.info("保存技术工艺接口异常,参数:{}", JSON.toJSONString(technologyBuilder.bulid()));
            throw BusinessExceptionFactory.newException("保存技术工艺接口异常");
        }
        //删除
        baseTechnologyRecordService.deleteByTechCode(editParams.getTechnologyCode(),loginUser);
        //保存工艺
        List<String> keys = new ArrayList<>();
        List<BaseTechnologyRecord> records = editParams.getGoods().stream().map(technologyGoodsParams -> {
            if(keys.contains(technologyGoodsParams.getKey())){
                log.info("原料重复:{}",technologyGoodsParams.getKey());
                throw  BusinessExceptionFactory.newException("原料重复");
            }
            TechnologyRecordBuilder technologyRecordBuilder = new TechnologyRecordBuilder();
            technologyRecordBuilder.appendStatus(YesOrNoEnum.YES.getValue()).appendCode(technologyBuilder.getCode())
                    .append(technologyGoodsParams).appendCreate(loginUser);
            return technologyRecordBuilder.bulid();
        }).collect(Collectors.toList());
        baseTechnologyRecordService.saveBatch(records);

        //保存扩展信息
        //查询信息 需要配置属性
        Map<String, String> tempMap = baseTemplateService.listByComapnyCode(TemplateTypeEnum.TECH.getValue(), loginUser)
                .stream().collect(Collectors.toMap(item -> item.getProp(), item -> item.getName()));
        List<String> existProp = new ArrayList<>();
        baseTemplateExtendService.deleteTemplateExtend(editParams.getTechnologyCode(),loginUser);
        baseTemplateExtendService.saveBatch(editParams.getProps().stream().map(templateRecord -> {
            TemplateExtendBuilder templateExtendBuilder = new TemplateExtendBuilder();
            String name = tempMap.get(templateRecord.getProp());
            if(StrUtil.isBlank(name)){
                log.info("属性{}不存在",templateRecord.getProp());
                throw BusinessExceptionFactory.newException("属性不存在");
            }
            if(existProp.contains(templateRecord.getProp())){
                log.info("属性{}存在重复",templateRecord.getProp());
                throw BusinessExceptionFactory.newException("属性重复");
            }
            existProp.add(templateRecord.getProp());
            templateExtendBuilder.append(templateRecord).appendCode(editParams.getTechnologyCode())
                    .appendCompanyCode(loginUser.getCompanyCode()).appendName(name)
                    .appendCreate(loginUser);
            return templateExtendBuilder.bulid();
        }).collect(Collectors.toList()));
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, technologyBuilder.getCode());
    }

    /**
     * 物料详情
     *
     * @param modelCode 物料编码
     * @return Result
     */
    public Result<TechnologyVO> viewTechnology(String modelCode) {
        ValidateUtil.hasLength(modelCode, "参数[modelCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询规格是否存在
        MaterialModelVO materialModel = goodsService.queryGoodsByCode(modelCode,loginUser);
        new AbstractCheck<>(materialModel).checkNull("规格不存在");
        //获取权限信息
        BaseTechnology baseTechnology = baseTechnologyService.queryTechnologyByModelCode(modelCode, loginUser);
        TechnologyVO technologyVO = new TechnologyVO();
        BeanUtil.copyProperties(materialModel,technologyVO);
        if(ObjectUtil.isNotNull(baseTechnology)){
            technologyVO.setTechnologyCode(baseTechnology.getTechnologyCode());
            technologyVO.setStepMothed(baseTechnology.getStepMothed());
            technologyVO.setRemark(baseTechnology.getRemark());
            //工艺原料
            List<BaseTechnologyRecord> records = baseTechnologyRecordService.listByTechnologyCode(baseTechnology.getTechnologyCode(), loginUser);
            if(ObjectUtil.isNotEmpty(records)){
                List<TechnologyGoodsVO> goodsVOS = records.stream().map(baseTechnologyRecord -> {
                    TechnologyGoodsVO technologyGoodsVO = new TechnologyGoodsVO();
                    //查询规格是否存在
                    MaterialModelVO materialModelVO = goodsService.queryGoodsByCode(baseTechnologyRecord.getModelCode(),loginUser);
                    BeanUtil.copyProperties(materialModelVO,technologyGoodsVO);
                    BeanUtil.copyProperties(baseTechnologyRecord,technologyGoodsVO);
                    return  technologyGoodsVO;
                }).collect(Collectors.toList());
                technologyVO.setGoods(goodsVOS);
            }
        }else {
            technologyVO.setTechnologyCode(CodeCreateUtil.getCode(Perifx.CODE));
        }
        //获取扩展信息
        Map<String, BaseTemplateExtend> extendMap = baseTemplateExtendService.listByObjectCode(technologyVO.getTechnologyCode()).stream()
                .collect(Collectors.toMap(item -> item.getProp(), item -> item));
        //获取属性信息
        List<PropVO> propVOS = baseTemplateService.listByComapnyCode(TemplateTypeEnum.TECH.getValue(),loginUser).stream().map(baseTemplate -> {
            return new PropBuilder().append(baseTemplate).append(extendMap.get(baseTemplate.getProp())).bulid();
        }).collect(Collectors.toList());
        technologyVO.setProps(propVOS);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, technologyVO);
    }
}
